<template>
  <div class="info-cards">
    <bread class="filter">
      <h1>学院资料夹</h1>
      <small>资料夹内容将向加入学院的全体老师展示，您可在此添加诸如对公账号、机构链接等学院等常用信息</small>
      <div class="pull-right" v-if="!showDraggable">
        <el-button
          :plain="true"
          size="small"
          @click="draggableSetting">
          拖拽排序
        </el-button>
        <el-button
          :plain="true"
          size="small"
          @click="showSetting">
          展示设置
        </el-button>
      </div>
      <div class="pull-right" v-else>
        <el-button
          :plain="true"
          type="text"
          size="small"
          @click="cancelSort">
          取消排序
        </el-button>
        <el-button
          :plain="true"
          size="small"
          @click="comfirmSort">
          保存
        </el-button>
      </div>
    </bread>
    <page-content>
      <div class="cards-wrap">
        <draggable v-if="pageData && pageData.length" v-model="pageData" :options="dragOptions">
          <transition-group type="transition" :name="'flip-list'">
            <form-edit
              v-for="infoCard in pageData"
              ref="formCard"
              class="info-card"
              :key="infoCard.id"
              :infoData="infoCard"
              :class="{canDraggable: isDraggable}"
              @remove="remove"
              @cancelOtherOperate="cancelOtherOperate"
              @canOperate="canOperate" />
          </transition-group>
        </draggable>
        <el-row>
          <el-card class="box-card add-wrap" v-show="showAdd">
            <div class="add" @click="addCard">
              <span>
                <i class="el-icon-plus"></i>
                添加一个新模块
              </span>
            </div>
          </el-card>
        </el-row>
      </div>
    </page-content>
    <el-dialog
      :visible.sync="infoCardsSettingVisible"
      size="tiny"
      :modal-append-to-body="false"
      title="学院资料夹设置"
      @close="infoCardsSettingVisible = false">
      <p>将学院常用信息如各类网址、常用文本等展示给已加入学院的成员，方便他们随时使用。</p>
      <div class="settings-form">
        <span>资料夹展示</span>
        <el-radio-group class="input-group" v-model="showInfoCards">
          <el-radio class="radio line" :label="1">展示</el-radio>
          <el-radio class="radio line" :label="0">不展示（不推荐）</el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="infoCardsSettingVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSettings" :loading="saveSettingLoading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import formEdit from './formEdit';
import draggable from 'vuedraggable';

// import { getInfoCards, toggleToolsVisible, sortInfoCards } from 'api';

export default {
  mounted() {
    // mock数据
    window.show_infocards = 1;
    this.$store.dispatch('get_signature', this)
  },
  data() {
    return {
      pageData: [],
      infoCardsSettingVisible: false,
      showInfoCards: Number(window.show_infocards),
      showAdd: false,
      obj: {},
      isDraggable: false, // 是否可以排序
      showDraggable: false, // 显示排序时的选项
      saveSettingLoading: false,
    }
  },
  beforeRouteLeave (to, from, next) {
    this.canOperate(() => {
      next();
    })
  },
  computed: {
    dragOptions () {
      return {
        disabled: !this.isDraggable,
        chosenClass: 'chosen-item',
      };
    },
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData(params) {
      this.$$api_researchTools_getInfoCards({
        succFn: (res) => {
          this.pageData = res;
          this.showAdd = true;
        }
      })

      // getInfoCards(params)
      //   .then(res => {
      //     this.pageData = res.data;
      //     console.log(this.pageData);
      //     this.$root.loading.visible = false;
      //     this.showAdd = true;
      //   })
      //   .catch(err => {
      //     this.$message.error(err.message)
      //   })
    },
    saveSettings() {
      this.saveSettingLoading = true;
      toggleToolsVisible({tool: 'infocards', show: this.showInfoCards})
      .then(res => {
        this.saveSettingLoading = false;
        this.$message.success('设置成功');
        window.show_infocards = this.showInfoCards;
        this.infoCardsSettingVisible = false;
      }).catch(err => {
        this.$message.error(err);
        this.saveSettingLoading = false;
      });
    },
    addCard() {
      this.canOperate(() => {
        this.$nextTick(() => {
          this.pageData.push({
            title: '',
            content: '',
            id: 0,
            enabled: 1,
            imglist: [],
          })
        })
      })
    },
    // 当新创建的时候点取消子组件通知父组件移除这个临时数据
    remove(obj) {
      const index = this.pageData.indexOf(obj);
      this.pageData.splice(index, 1);
    },
    // updateInfo(itemIndex, obj) {
    //   this.$set(this.pageData, itemIndex, obj);
    // },
    // 点击展示设置
    showSetting() {
      this.canOperate(() => {
        this.infoCardsSettingVisible = true;
        this.showInfoCards = Number(window.show_infocards);
      })
    },
    // 点击拖拽排序
    draggableSetting() {
      this.canOperate(() => {
        this.showDraggable = true;
        this.isDraggable = true;
      })
    },
    canOperate(operateCallback) {
      const currentEdit = this.$refs.formCard ? this.$refs.formCard.filter(item => item.editing == true) : [];
      if (currentEdit.length > 0) {
        this.$confirm('当前编辑中内容尚未保存，是否保存？注意：内容一旦保存将对全体职工可见。', '学院资料夹', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          currentEdit[0].submitForm(() => {
            operateCallback && operateCallback();
          });
        }).catch(() => {
          currentEdit[0].cancelEdit(() => {
            operateCallback && operateCallback();
          });
        });
      } else {
        operateCallback && operateCallback();
      }
    },
    cancelSort() {
      this.showDraggable = false;
      this.isDraggable = false;
      this.list = this.pageData.sort((one, two) =>{return two.sort - one.sort;})
    },
    comfirmSort() {
      let sortData = [];
      this.pageData.forEach((item, index) => {
        sortData.push({id: item.id, order: index});
        item.order = index;
        this.showDraggable = false;
        this.isDraggable = false;
      })
      // sortInfoCards({orders: JSON.stringify(sortData)})
      // .then(() =>{
      // })
      this.$$api_researchTools_sortInfoCards({
        data: {orders: JSON.stringify(sortData)},
        succFn: (res) => {
          console.log('排序成功', res);
        }
      })
    },
    // 编辑状态取消排序
    cancelOtherOperate() {
      this.cancelSort();
    }
  },
  components: {
    formEdit,
    draggable,
  }
}
</script>
<style scoped lang="scss">
.cards-wrap {
  padding: 30px 20px;
}
.settings-form {
  display: flex;
  margin-top: 20px;
  > span {
    flex: 1;
  }
  .input-group {
    flex: 3;
    display: flex;
    flex-direction: column;
  }
  .el-radio + .el-radio {
    margin-left: 0;
    margin-top: 20px;
  }
}
.add {
  padding: 20px;
  text-align: center;
  font-size: 20px;
  color: #C0CCDA;
  cursor: pointer;
}
.flip-list-move {
  transition: transform 0.5s;
}
.no-move {
  transition: transform 0.5s;
}
.info-card {
  &.canDraggable {
    cursor: move;
  }
}
</style>
<style lang="scss">
.info-cards {
  .chosen-item {
    .box-card {
      background: rgba(192,217,237,0.50);
      border: 1px solid #20A0FF;
    }
  }
}
.add-wrap {
  .el-card__body {
  padding: 0;
  }
}
</style>

